package com.lagou.demo.interceptor;

import com.lagou.edu.mvcframework.Interceptor.HandlerInterceptor;
import com.lagou.edu.mvcframework.annotations.Security;
import com.lagou.edu.mvcframework.pojo.Handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;

public class DemoSecurityInterceptor implements HandlerInterceptor {

    private static final String USERNAME_FILED = "username";

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Handler handler) {
        String username = req.getParameter(USERNAME_FILED);

        // 检查是否需要做权限校验
        Security security = handler.getSecurity();
        if (security != null && !hasPermission(security, username)) {
            showNoPermissionView(resp);
            return false;
        }

        return true;
    }

    /**
     * 检查是否有权限
     *
     * @param security
     * @return
     */
    private boolean hasPermission(Security security, String username) {
        String[] usernames = security.value();
        if (usernames != null && usernames.length > 0) {
            boolean passed = Arrays.stream(usernames).anyMatch(u -> u.equals(username));
            if (!passed) {
                System.out.println(String.format("no permission, username=%s, securityUsers=%s",
                        username, String.join(",", usernames)));
            }
            return passed;
        }
        return true;
    }

    /**
     * 无权限页面展示
     *
     * @param resp
     */
    private void showNoPermissionView(HttpServletResponse resp) {
        try {
            resp.getWriter().println("<h1>抱歉，您没有权限访问此接口！</h1>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void postHandle(HttpServletRequest req, HttpServletResponse resp, Handler handler) {

    }
}
